package fr.gedos.ged.classifier.core.entities.dao.impl;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;

import fr.gedos.ged.classifier.core.entities.dao.GenericDAO;

/**
 * 
 * Hibernate generic class.
 * @author Marshall
 * @param <T>
 */
public class GenericDAOImp<T> implements GenericDAO<T> {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /** Persistent class. */
    private final Class<T> persistentClass;

    /** Hibernate Factory. */
    @Autowired
    private SessionFactory sessionFactory;

    /** Default Constructor. */
    @SuppressWarnings("unchecked")
    protected GenericDAOImp() {
        this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
    }

    /**
     * GET session.
     * 
     * @return Hibernate session
     */
    protected Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }

    /**
     * Getter of the persistent class.
     * 
     * @return persistent class
     */
    public Class<T> getPersistentClass() {
        return persistentClass;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pharmagest.tools.gconf.changelog.dao.GenericDao#load(java.lang.Long)
     */
    @SuppressWarnings("unchecked")
    public T load(final Long id) {
        return (T) getSession().load(getPersistentClass(), id);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pharmagest.tools.gconf.changelog.dao.GenericDao#get(java.lang.Long)
     */
    @SuppressWarnings("unchecked")
    public T get(final Long id) {
        return (T) getSession().get(getPersistentClass(), id);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pharmagest.tools.gconf.changelog.dao.GenericDao#saveOrUpdate(java.lang.Object)
     */
    public T saveOrUpdate(final T entity) {
        getSession().saveOrUpdate(entity);
        return entity;
    }

    public T save(final T entity) {
        getSession().save(entity);
        return entity;
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pharmagest.tools.gconf.changelog.dao.GenericDao#refresh(java.lang.Object)
     */
    public void refresh(final T entity) {
        getSession().refresh(entity);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.pharmagest.tools.gconf.changelog.dao.GenericDao#delete(java.lang.Object)
     */
    public void delete(final T entity) {
        getSession().delete(entity);
    }

    /**
     * flush session.
     */
    public void flush() {
        getSession().flush();
    }

    /**
     * clear the session.
     */
    public void clear() {
        getSession().clear();
    }

}
